package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("dish")
public class DishController {
    @Autowired
    private DishService dishService;

    //分页查询
    @GetMapping("page")
    public R<Page<DishDto>> selectByPage(Integer page, Integer pageSize, String name) {
        Page<DishDto> pageInfo = dishService.pageDishDto(page,pageSize,name);
        return R.success(pageInfo);
    }

    //根据id查询回显数据
    @GetMapping("{id}")
    public R<Dish> selectById(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }
    //修改菜品
    @PutMapping()
    @CacheEvict(cacheNames = "dish",allEntries = true) //删除所有以dish开头的缓存
    public R update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        return R.success("修改成功");
    }
    //修改状态
    @PostMapping("status/{status}")
    @CacheEvict(cacheNames = "dish",allEntries = true) //删除所有以dish开头的缓存
    public R updateStatus(@PathVariable Integer status,Long[] ids){
        dishService.lambdaUpdate()
                .set(Dish::getStatus,status)
                .in(Dish::getId,ids)
                .update();
        return R.success("修改成功");
    }

    //添加菜品
    @PostMapping()
    @CacheEvict(cacheNames = "dish",allEntries = true) //删除所有以dish开头的缓存
    public R add(@RequestBody DishDto dishDto){
        dishService.savewithFlavor(dishDto);
        return R.success("添加成功");
    }
    //批量删除
    @DeleteMapping()
    @CacheEvict(cacheNames = "dish",allEntries = true) //删除所有以dish开头的缓存
    public R removeByIds(@RequestParam List<Long> ids){
        dishService.deleteWithFlavor(ids);
        return R.success("删除成功");
    }

    //移动端展示菜品及口味  及后端添加套餐中的添加菜品展示
    @GetMapping("list")
    @Cacheable(cacheNames = "dish",key = "#categoryId+'_'+#name",unless ="#result.data.size()<=0" )
    public R list(Long categoryId,String name){
        List<DishDto> list = dishService.listDishDto(categoryId,name);
        return R.success(list);
    }
}
